﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Threading.Tasks;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Logic.Statistics;
using Atmk.WaterMeter.MIS.Commons.Utils;
using Atmk.WaterMeter.MIS.Commons.ViewModels.Chart;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Models;
using NLog;

namespace Atmk.WaterMeter.MIS.Logic.Mock
{
    public class ChartLogicMock : IChartLogic
    {
        protected Logger _logger = LogManager.GetCurrentClassLogger();
        private Dictionary<string, int> _MonthCount = new Dictionary<string, int>();

        //费用提醒 已关阀
        public async Task<ChartDatas> FYTX_YGF(string projectId)
        {
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    var chatResult = new ChartDatas();
                    //费用提醒
                    chatResult.costReminderData = await GetCostReminderData();
                    //关阀提醒
                    chatResult.closingvalveData = await GetClosingvalveData();
                    return chatResult;
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public StatisticsInfoData Top1(string projectId)
        {
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    //首页小模块（统计信息）
                    //排除库房的表
                    string[] errorDistricts = { "329d958e-a56f-4af6-b6bb-40da437bbcdc" };
                    string[] ctdeviceIds = _context.Meter.Where(m => !errorDistricts.Contains(m.DistrictId) && m.ProjectId == projectId).Select(m => m.CtdeviceId).ToArray();

                    var district_ids = _context.District.Where(m => m.ProjectId == projectId && !errorDistricts.Contains(m.Id)).Select(m => m.Id).ToArray();
                    var owners = _context.Owner.Where(m => district_ids.Contains(m.DistrictId)).ToList();
                    //在线率
                    var num = Convert.ToDouble((_context.SettlementDay.Where(m => m.ReadTime.Date >= DateTime.Now.AddDays(-3).Date && ctdeviceIds.Contains(m.CtdeviceId)).GroupBy(m => m.CtdeviceId).Count() / Convert.ToDouble(ctdeviceIds.Count()) * 100).ToString("f2"));
                    var statisticsInfoData = new StatisticsInfoData
                    {
                        districtCount = district_ids.Count(),
                        meterCount = ctdeviceIds.Count(),
                        ownerCount = owners.Count(),
                        onlineRatio = num
                    };
                    return statisticsInfoData;
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public WaterConsumptionInfoData Top3_4(string projectId)
        {
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    //排除库房的表
                    string[] errorDistricts = { "329d958e-a56f-4af6-b6bb-40da437bbcdc" };
                    var district_ids = _context.District.Where(m => m.ProjectId == projectId && !errorDistricts.Contains(m.Id)).Select(m => m.Id).ToArray();

                    WaterConsumptionInfoData waterConsumptionInfoData = new WaterConsumptionInfoData
                    {
                        yesterday = (int)_context.TopSelect.Where(m => m.CreateDate == DateTime.Now.AddDays(-1).Date && district_ids.Contains(m.DistrictId)).Sum(m => m.Dosage),
                        nowMonth = (int)_context.TopSelect.Where(m => m.CreateDate.Value.Year == DateTime.Now.Year && m.CreateDate.Value.Month == DateTime.Now.Month && district_ids.Contains(m.DistrictId)).Sum(m => m.Dosage),
                        lastMonth = (int)_context.TopSelect.Where(m => m.CreateDate.Value.Year == DateTime.Now.AddMonths(-1).Year && m.CreateDate.Value.Month == DateTime.Now.AddMonths(-1).Month && district_ids.Contains(m.DistrictId)).Sum(m => m.Dosage),
                        sameMonth = (int)_context.TopSelect.Where(m => m.CreateDate.Value.Year == DateTime.Now.AddYears(-1).Year && m.CreateDate.Value.Month == DateTime.Now.Month && district_ids.Contains(m.DistrictId)).Sum(m => m.Dosage),

                        yearDosage = (int)_context.TopSelect.Where(m => m.CreateDate.Value.Year == DateTime.Now.Year && district_ids.Contains(m.DistrictId)).Sum(m => m.Dosage),
                        lastYearDosage = (int)_context.TopSelect.Where(m => m.CreateDate.Value.Year == DateTime.Now.AddYears(-1).Year && district_ids.Contains(m.DistrictId)).Sum(m => m.Dosage),
                        sameYear = (int)_context.TopSelect.Where(m => m.CreateDate > Convert.ToDateTime(DateTime.Now.AddYears(-1).Year + "-01-01") && m.CreateDate <= DateTime.Now.AddYears(-1).Date && district_ids.Contains(m.DistrictId)).Sum(m => m.Dosage)
                    };

                    return waterConsumptionInfoData;
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #region private

        //上年用量
        public YearWaterConsumptionsCountData GetLastYearWaterDosage(string projectId)
        {
            try
            {
                #region 旧版代码
                //using (var _context = ContextBuilder.Build())
                //{
                //    var districts = _context.District.Where(m => m.ProjectId == projectId);
                //    var meter_group = _context.Meter.Where(m => m.ProjectId == projectId).GroupBy(m => m.DistrictId);
                //    //取日结算表上个月的数据
                //    var settlementDays = _context.SettlementDay.Where(m => m.ReadTime.Year == DateTime.Now.AddYears(-1).Year).GroupBy(m => m.ReadTime.Month).ToList();

                //    var r = new YearWaterConsumptionsCountData
                //    {
                //        total = "0",
                //        list = new List<WaterConsumptionsCountListItem>(),
                //        year = DateTime.Now.Year
                //    };
                //    foreach (var item in meter_group)
                //    {
                //        var tempp = new WaterConsumptionsCountListItem
                //        {
                //            districtId = item.Key,
                //            districtName = districts.FirstOrDefault(m => m.Id == item.Key)?.Name,
                //            waterConsumptions = new List<double>()
                //        };
                //        foreach (var item1 in settlementDays)
                //        {
                //            var dcs = item.Select(m => m.CtdeviceId);//片区下的所有CtdeviceId
                //            tempp.waterConsumptions.Add(item1.Where(m => dcs.Contains(m.CtdeviceId)).Sum(m => m.Dosage));
                //        }
                //        tempp.waterConsumptions.Reverse();
                //        for (int i = 0; i < 12 - settlementDays.Count; i++)
                //        {
                //            tempp.waterConsumptions.InsertRange(0, new List<double>() { 0 });
                //        }
                //        r.list.Add(tempp);
                //    }

                //    return r;
                //} 
                #endregion
                using (var _context = ContextBuilder.Build()) 
                {
                    //排除库房的表
                    string[] errorDistricts = { "329d958e-a56f-4af6-b6bb-40da437bbcdc" };
                    var districts = _context.District.Where(m => m.ProjectId == projectId && !errorDistricts.Contains(m.Id)).ToList();
                    var district_ids = districts.Select(m => m.Id);
                    var topselects = _context.TopSelect.Where(m => m.CreateDate.Value.Year == DateTime.Now.AddYears(-1).Year && district_ids.Contains(m.DistrictId)).ToList();
                    var r = new YearWaterConsumptionsCountData
                    {
                        total = "0",
                        list = new List<WaterConsumptionsCountListItem>(),
                        year = DateTime.Now.AddYears(-1).Year
                    };
                    foreach (var district in districts)
                    {
                        var tempp = new WaterConsumptionsCountListItem
                        {
                            districtId = district.Id,
                            districtName = district.Name,
                            waterConsumptions = new List<double>()
                        };

                        for (int i = 1; i < 13 ; i++)
                        {
                            double dosage = (double)topselects.Where(m => m.CreateDate.Value.Month == i&&m.DistrictId== district.Id).Sum(m => m.Dosage);
                            tempp.waterConsumptions.Add(dosage);
                        }
                        r.list.Add(tempp);
                    }
                    return r;
                }
            }
            catch (Exception ex)
            {
                _logger.Error("首页小模块取数错误（月用水量）：" + ex.Message);
                return new YearWaterConsumptionsCountData() { total = "0", list = null, year = 1999 };
            }
        }

        //上季度用量
        public WaterConsumptionsCountData GetLastSeasonDosage(string projectId)
        {
            using (var _context = ContextBuilder.Build())
            {
                //排除库房的表
                string[] errorDistricts = { "329d958e-a56f-4af6-b6bb-40da437bbcdc" };
                var districts = _context.District.Where(m => m.ProjectId == projectId && !errorDistricts.Contains(m.Id)).ToList();
                var r = new WaterConsumptionsCountData
                {
                    total = "0",
                    list = new List<WaterConsumptionsCountListItem>()
                };
                foreach (var district in districts)
                {
                    List<double> temp = new List<double>();
                    for (int i = 0; i < 3; i++)
                    {
                        temp.Add((double)_context.TopSelect.Where(m => m.CreateDate.Value.Year == DateTime.Now.AddMonths(-i).Year && m.CreateDate.Value.Month == DateTime.Now.AddMonths(-i).Month && district.Id == m.DistrictId).Sum(m => m.Dosage));
                    }
                    r.list.Add(new WaterConsumptionsCountListItem
                    {
                        districtId = district.Id,
                        districtName = district.Name,
                        waterConsumptions = temp
                    });
                }
                return r;
            }
        }

        //上月用水量
        public WaterConsumptionsCountData GetLastMonthDosage(string projectId)
        {
            try
            {
                using (var _context = ContextBuilder.Build())
                {
                    //排除库房的表
                    string[] errorDistricts = { "329d958e-a56f-4af6-b6bb-40da437bbcdc" };
                    var districts = _context.District.Where(m => m.ProjectId == projectId && !errorDistricts.Contains(m.Id)).ToList();
                    var r = new WaterConsumptionsCountData
                    {
                        total = districts.Count().ToString(),
                        list = new List<WaterConsumptionsCountListItem>()
                    };
                    foreach (var district in districts)
                    {
                        r.list.Add(new WaterConsumptionsCountListItem
                        {
                            districtId = district.Id,
                            districtName = district.Name,
                            waterConsumptions = new List<double>() { (double)_context.TopSelect.Where(m => m.CreateDate.Value.Year == DateTime.Now.AddMonths(-1).Year && m.CreateDate.Value.Month == DateTime.Now.AddMonths(-1).Month && district.Id == m.DistrictId).Sum(m => m.Dosage) }
                        });
                    }
                    return r;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

        }


        private YesterdayConsumptionData GetYesterdayConsumptionData()
        {
            var r = new YesterdayConsumptionData
            {
                total = 3.ToString(),
                list = new List<YesterdayConsumptionListItem>()
            };
            for (var i = 0; i < 3; i++)
            {
                var item = new YesterdayConsumptionListItem
                {
                    ownerId = Guid.NewGuid().ToString(),
                    houseNumber = $"门牌号{i + 1}",
                    waterConsumption = new Random(Simple.GetRandomSeed()).Next(1500, 3680)
                };
                r.list.Add(item);
            }
            return r;
        }

        //各片区抄表情况 
        public DistrictReadRatioData GetDistrictReadRatioData()
        {
            var len = ChartDateCatchMock.DistrictList.Length;
            var r = new DistrictReadRatioData
            {
                total = len.ToString(),
                list = new List<DistrictReadRatioItem>()
            };
            for (var i = 0; i < len; i++)
            {
                var dicName = ChartDateCatchMock.DistrictList[i];
                var item = new DistrictReadRatioItem
                {
                    districtId = Guid.NewGuid().ToString(),
                    districtName = $"{dicName}",
                    readRatio = (new Random(Simple.GetRandomSeed()).Next(9000,
                                    10000)) / 100.00
                };
                r.list.Add(item);
            }
            return r;
        }
        //关门阀 的业主
        private Task<ClosingvalveData> GetClosingvalveData()
        {
            return Task.Run(() =>
            {
                using (var _context = ContextBuilder.Build())
                {
                    var temp = new List<MeterReadingRecord>();
                    var mrr_group = _context.MeterReadingRecord.Where(m => m.ReadTime > DateTime.Now.AddDays(-31)).GroupBy(m => m.CtdeviceId).Select(m => m.OrderByDescending(m1 => m1.ReadTime)).ToList();
                    //var mrr_group = _context.MeterReadingRecord.GroupBy(m => m.CtdeviceId).Select(m => m.OrderByDescending(m1 => m1.ReadTime)).ToList(); //未优化语句
                    foreach (var item in mrr_group)
                    {
                        if (item.First().ValveState == 0)
                        {
                            temp.Add(item.First());
                        }
                    }
                    string[] CtdeviceIds = temp.Select(m => m.CtdeviceId).ToArray();
                    var ownerids = _context.Meter.Where(m => CtdeviceIds.Contains(m.CtdeviceId)).Select(m => m.OwnerId).ToArray();
                    var owners = _context.Owner.Where(m => ownerids.Contains(m.Id)).ToList();
                    var r = new ClosingvalveData
                    {
                        total = mrr_group.Count().ToString(),
                        list = new List<ClosingValveOwnerItem>()
                    };
                    foreach (var item in owners)
                    {
                        r.list.Add(new ClosingValveOwnerItem()
                        {
                            ownerId = item.Id,
                            houseNumber = item.HouseNumber,
                            ownerName = item.Name
                        });
                    }
                    return r;
                }
            });
        }
        //费用提醒
        private Task<CostReminderData> GetCostReminderData()
        {
            return Task.Run(() =>
            {
                using (var _context = ContextBuilder.Build())
                {
                    var orderDetails = _context.OrderDetail.GroupBy(m => m.OwnerId);
                    var order30 = orderDetails.OrderBy(m => m.Sum(m1 => m1.Money)).Take(20).ToList();
                    string[] order_ownerids = order30.Select(m1 => m1.Key).ToArray();
                    var owners = _context.Owner.Where(m => order_ownerids.Contains(m.Id)).ToList();
                    var r = new CostReminderData
                    {
                        total = order30.Count().ToString(),
                        list = new List<CostReminderItem>()
                    };
                    foreach (var item in order30)
                    {
                        Owner owner = owners.FirstOrDefault(m => m.Id == item.Key);
                        if (owner==null)
                        {
                            continue;
                        }
                        else
                        {
                            r.list.Add(new CostReminderItem()
                            {
                                ownerId = item.Key,
                                ownerName = owners.First(m1 => m1.Id == item.Key).Name,
                                balance = item.Sum(m1 => m1.Money)
                            });
                        }
                    }
                    r.list = r.list.OrderBy(m => m.balance).Take(30).ToList();
                    return r;
                }
            });
        }

        //前三天用量
        public WaterConsumptionsCountData GetFirstThreeDays(string projectId)
        {
            using (var _context = ContextBuilder.Build())
            {
                //排除库房的表
                string[] errorDistricts = { "329d958e-a56f-4af6-b6bb-40da437bbcdc" };
                var districts = _context.District.Where(m => m.ProjectId == projectId && !errorDistricts.Contains(m.Id)).ToList();
                var district_ids = districts.Select(m1 => m1.Id);

                var TopSelect = _context.TopSelect.Where(m => m.CreateDate >= DateTime.Now.AddDays(-4)&& district_ids.Contains(m.DistrictId)).ToList();
                var r = new WaterConsumptionsCountData
                {
                    total = "0",
                    list = new List<WaterConsumptionsCountListItem>()
                };
                foreach (var district in districts)
                {
                    List<double> temp = new List<double>();
                    temp.Add((double)TopSelect.Where(m => m.CreateDate.Value.Date == DateTime.Now.AddDays(-1).Date&& district.Id==m.DistrictId).Sum(m => m.Dosage));
                    temp.Add((double)TopSelect.Where(m => m.CreateDate.Value.Date == DateTime.Now.AddDays(-2).Date && district.Id == m.DistrictId).Sum(m => m.Dosage));
                    temp.Add((double)TopSelect.Where(m => m.CreateDate.Value.Date == DateTime.Now.AddDays(-3).Date && district.Id == m.DistrictId).Sum(m => m.Dosage));

                    r.list.Add(new WaterConsumptionsCountListItem
                    {
                        districtId = district.Id,
                        districtName = district.Name,
                        waterConsumptions = temp
                    });
                }
                return r;
            }
        }
        #endregion

    }
}